<template>
  <div id="app">

    <!-- 新增表单 -->
    <el-dialog center title="入库申请" :visible.sync="addFormView">
      <el-form label-position="left" label-width="80px" :model="add">
        <el-form-item label="商品">
          <el-select v-model.number="add.goodsId" placeholder="请选择商品">
            <el-option v-for="item in goodsOptions"
                       :key="item.id"
                       :label="item.goodsName"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品数量">
          <el-input-number size="small" min="1" v-model.number="add.buyCount"></el-input-number>
        </el-form-item>
        <el-form-item label="进货单价">
          <el-input v-model="add.price" placeholder="进货单价" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="总价">
          <el-input v-model="totalPrice" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormView = false">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改表单 -->
    <el-dialog title="修改" :visible.sync="updateFormView">
      <el-form label-position="left" label-width="80px" :model="update">
        <el-form-item v-if="update.backReason" label="驳回原因">
          {{ update.backReason }}
        </el-form-item>
        <el-form-item label="商品名">
          <el-input v-model="update.goodsName" :disabled="update.status === 2 || update.empId !== userId"></el-input>
        </el-form-item>
        <el-form-item label="商品数量">
          <el-input-number :disabled="update.status === 2 || update.empId !== userId" size="small" min="1"
                           v-model.number="update.buyCount"></el-input-number>
        </el-form-item>
        <el-form-item label="进货单价">
          <el-input v-model="update.price" :disabled="update.empId !== userId" placeholder="进货单价" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="总价">
          <el-input v-model="updateTotalPrice" disabled></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="updateFormView = false">取 消</el-button>
        <el-button type="primary" @click="submitUpdateForm">确 定</el-button>
        <el-button v-show="userType === 9" type="success" @click="submitPass">通过审核</el-button>
        <el-button v-show="userType === 9" type="danger" @click="submitBack">驳回</el-button>
      </template>
      <el-dialog append-to-body title="驳回原因" :visible.sync="backFormView">
        <el-form ref="backForm" label-position="left" label-width="80px" :model="update" :rules="rules">
          <el-form-item label="驳回原因" prop="backReason">
            <el-input type="textarea" v-model="update.backReason" placeholder="驳回原因" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="backFormView = false">取 消</el-button>
          <el-button type="primary" @click="submitBackForm('backForm')">确 定</el-button>
        </template>
      </el-dialog>
    </el-dialog>

    <!-- 搜索框 -->
    <el-card class="box-card" shadow="always">
      <el-input
        placeholder="商品名"
        v-model="selectBuy.goodsName"
        size="medium">
      </el-input>
      <el-input
        placeholder="申请人"
        v-model="selectBuy.name"
        size="medium">
      </el-input>
      <el-button type="info" size="medium" @click="getBuyList" plain>查询</el-button>
      <el-button type="warning" size="medium" @click="handelRecet" plain>重置</el-button>
    </el-card>
    <!-- 操作框 -->
    <el-card class="box-card" shadow="always">
      <el-button type="primary" size="medium" @click="addFormView = true" plain>申请入库</el-button>
    </el-card>

    <!-- 表格以及分页 -->
    <el-card shadow="always">
      <el-table
        :data="tableData"
        style="width: 100%"
        height="415">
        <el-table-column
          label="商品名"
          prop="goodsName">
        </el-table-column>
        <el-table-column
          label="图片"
          align="center"
          width="150">
          <template slot-scope="scope">
            <el-image
              :src="scope.row.goodsImg"
              fit="cover">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
          label="申请人"
          align="center"
          prop="name">
        </el-table-column>
        <el-table-column
          label="进货数量"
          width="100"
          align="center"
          prop="buyCount">
        </el-table-column>
        <el-table-column
          label="进货单价"
          align="center"
          prop="price">
        </el-table-column>
        <el-table-column
          label="进货总价"
          align="center"
          prop="totalPrice">
        </el-table-column>
        <el-table-column
          label="进货日期"
          prop="buyDate">
        </el-table-column>
        <el-table-column
          label="入库状态"
          prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="warning">待审核</el-tag>
            <el-tag v-if="scope.row.status === 2" type="success">已入库</el-tag>
            <el-tag v-if="scope.row.status === 0" type="danger">已驳回</el-tag>
          </template>
        </el-table-column>
        <el-table-column width="200" fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button
              v-show="scope.row.status !== 2"
              size="mini"
              @click="handleEdit(scope.row)">
              编辑
            </el-button>&nbsp;
            <el-button
              v-show="scope.row.status !== 2"
              type="danger"
              size="mini"
              slot="reference"
              @click="handelDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>

    </el-card>
  </div>

</template>

<script>
import { Message, MessageBox } from 'element-ui'
import { getGoods, buy, updateBuyInfo, deleteBuyInfo, passApi } from '@/api/buy'
import instance from '@/utils/request'

export default {
  name: 'BuyPage',
  data () {
    return {
      add: {
        goodsId: '',
        buyCount: '',
        price: '',
        totalPrice: ''
      },
      update: {
        goodsId: '',
        buyCount: '',
        price: '',
        totalPrice: '',
        status: '',
        backReason: ''
      },
      selectBuy: {
        name: '',
        goodsName: '',
        empId: ''
      },
      goodsOptions: [],
      updateFormView: false, // 修改表单显示
      addFormView: false, // 新增表单显示
      backFormView: false, // 驳回表单显示
      input1: '',
      input2: '',
      currentPage: 1, // 当前页
      pageSize: 5,
      total: 1,
      tableData: [],
      rules: {
        backReason: [
          {
            required: true,
            message: '请输入驳回原因',
            trigger: 'blur'
          }
        ]
      },
      backForm: null
    }
  },
  methods: {
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getBuyList()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getBuyList()
    },
    handleEdit (row) {
      this.updateFormView = true
      this.update = row
    },
    handelSelect () {
    },
    async submitPass () {
      if (this.update.status !== 1) {
        Message.error('只能通过待审核的申请！')
        return
      }
      this.update.backReason = ''
      const res = await passApi(this.update.id)
      Message.success(res.data)
      await this.getBuyList()
      this.updateFormView = false
    },
    submitBack () {
      if (this.update.status !== 1) {
        Message.error('只能驳回待审核的申请！')
        return
      }
      this.backFormView = true
    },
    async submitBackForm (formName) {
      await this.$refs[formName].validate()
      // await this.backForm.validate()
      this.update.status = 0
      await updateBuyInfo(this.update)
      Message.success('驳回成功！')
      await this.getBuyList()
      this.backFormView = false
      this.updateFormView = false
    },
    // 查询重置
    handelRecet () {
      this.selectBuy = {
        name: '',
        goodsName: ''
      }
      this.getBuyList()
    },
    handelAllDelete () {
      console.log('批量删除')
    },
    async submitAddForm () {
      this.addFormView = false
      this.add.totalPrice = this.totalPrice
      const res = await buy(this.add)
      Message.success(res.data)
      await this.getBuyList()
    },
    // 提交修改表单
    async submitUpdateForm () {
      this.updateFormView = false
      this.update.status = 1
      this.update.backReason = ''
      const res = await updateBuyInfo(this.update)
      Message.success(res.data)
      await this.getBuyList()
    },

    // 商品下拉框数据渲染
    async getGoodsList () {
      const res = await getGoods()
      this.goodsOptions = res.data
    },

    // 表格数据渲染
    // 渲染表格
    async getBuyList () {
      if (this.userType !== 9) {
        this.selectBuy.empId = this.userId
      }
      const res = await instance.post(`/buy/list/${this.currentPage}/${this.pageSize}`,
        this.selectBuy)
      this.tableData = res.data.list
      this.total = res.data.total
    },

    // 删除
    handelDelete (row) {
      const this_ = this
      MessageBox.confirm('确定删除该条进货申请?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBuyInfo(row)
        Message({
          type: 'success',
          message: '删除成功!'
        })
        this_.getBuyList()
      }).catch(() => {
        Message({
          type: 'info',
          message: '已取消删除'
        })
        this_.getBuyList()
      })
    }

  },

  computed: {
    totalPrice () {
      return (this.add.buyCount * this.add.price).toFixed(2)
    },
    updateTotalPrice () {
      return (this.update.buyCount * this.update.price).toFixed(2)
    },
    userType () {
      return this.$store.getters.userType
    },
    userId () {
      return this.$store.getters.id
    }
  },

  created () {
    // 渲染商品列表
    this.getGoodsList()
    // 渲染表格
    this.getBuyList()
  }

}
</script>

<style scoped>
.el-input {
  width: 200px;
  margin-right: 5px;
}

.el-card ::v-deep .el-card__body {
  padding: 10px;
}

.el-pagination {
  padding: 15px;
}
</style>
